/**
 * 
 */

/**
 * devices数据结构 { "001" : { "timestamp" : 121222323, data : { "id" : "0",
 * "deviceName" : "dRtv", "deviceType" : "SLA", "area" : "20-1000mm", "power" :
 * "1000w", "percent" : 64 } }, "002" : { "timestamp" : 121222323, data : { "id" :
 * "0", "deviceName" : "dRtv", "deviceType" : "SLA", "area" : "20-1000mm",
 * "power" : "1000w", "percent" : 64 } } }
 */
var vue = new Vue({
	el : '#app1',
	data : {
		devices : {}
	},
	mounted : function() {
		this.initData();
	},
	methods : {
		initData : function() {
			let _self = this;
			/*
			 * jQuery.getJSON("/api/devices", function(data) { _self.devices =
			 * data; });
			 */
		},
		dateFormat : function(time) {
			var date = new Date(time);
			var year = date.getFullYear();
			/*
			 * 在日期格式中，月份是从0开始的，因此要加0 使用三元表达式在小于10的前面加0，以达到格式统一 如 09:11:05
			 */
			var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
			var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
			var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
			var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
			var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
			// 拼接
			return year + "/" + month + "/" + day + " " + hours + ":" + minutes + ":" + seconds;
		}

	},
	ready : function() {
	}
})

// vue数据源作为数据库
var _DB = vue.devices
// 获取毫秒级时间戳
function getCreateTime() {
	return new Date().getTime()
	// return Date.parse(new Date()) / 1000
}
// 插入数据库
function insertDB(rowData) {
	_DB[rowData.id] = {
		createTime : getCreateTime,
		data : rowData
	}
}
// 从数据库删除
function deletFromeDB(key) {
	if (existInDB(key)) {
		delete _DB.key
	}
}
// 判断存在
function existInDB(key) {
	return !_DB.key == undefined
}
// 判断数据是否过期
function existInDB(key) {

}

var hostname = "127.0.0.1"; // 主机IP 106.14.181.32
var hostPort = 15675; // port
var sub_count = 0;
var client;
var clientId = "myclientid_" + parseInt(Math.random() * 100, 10);
function MQTTconnect() {
	client = new Paho.MQTT.Client(hostname, hostPort, '/ws', clientId);
	client.onMessageArrived = onMessageArrived;
	client.onConnectionLost = onConnectionLost;
	client.connect({
		timeout : 3,
		keepAliveInterval : 30,
		onSuccess : onConnect,
		onFailure : connectFail

	});
	console.log("Host=" + hostname + ", port=" + hostPort);

};
// 连接成功回调
function onConnect() {
	console.log("onConnect succeeds");
	client.subscribe('/device/info'); // 订阅所有主题
}
// 连接失败回调
function connectFail(message) {
	console.log("CONNECTION FAILURE - " + message.errorMessage);
}
// 连接断开回调
function onConnectionLost(responseObject) {
	if (responseObject.errorCode !== 0) {
		alert('diconneced');
		console.log("onConnectionLost:" + responseObject.errorMessage);
	}
}
// 接收到订阅消息回调
function onMessageArrived(message) {
	var topic = message.destinationName;
	var payload = message.payloadString;
	// vue.devices.push(JSON.parse(payload))
	// Vue.set(_DB, 1, JSON.parse(payload))
	// _DB.splice(0, 1, JSON.parse(payload))
	var obj = JSON.parse(payload)
	for ( let id in obj) {
		Vue.set(vue.devices, id, obj[id]);
	}
	// console.log("onMessageArrived:" + payload);
}
var testInfo = {
	"003" : {
		"timestamp" : 121222323,
		data : {
			"id" : "0",
			"deviceName" : "dRtv",
			"deviceType" : "SLA",
			"area" : "20-1000mm",
			"power" : "1000w",
			"percent" : 64
		}
	}
}

var topic = '/device/info';
// 发布消息
function publish(msg) {
	var message = new Paho.MQTT.Message(msg);
	message.destinationName = topic;
	message.qos = 0;
	client.send(message);
}

function getDeviceData(id, percent) {
	var data = {}
	data[id] = {
		"timestamp" : getCreateTime(),
		data : {
			"id" : "0",
			"deviceName" : "dRtv",
			"deviceType" : "SLA",
			"area" : "20-1000mm",
			"power" : "1000w",
			"percent" : percent
		}
	}
	return data
}
function init() {

	MQTTconnect();
	var percent1 = 77;
	var timeInterval1 = window.setInterval(function() {
		if (client.isConnected()) {
			if (percent1 >= 100) {
				percent1 = 10
			}
			var data = getDeviceData("001", percent1)
			var strData = JSON.stringify(data)
			publish(strData)
			percent1 = percent1 + 1
		}
	}, 2000);

	var percent2 = 10;
	var timeInterval2 = window.setInterval(function() {
		if (client.isConnected()) {
			if (percent2 >= 100) {
				percent2 = 10
			}
			var data = getDeviceData("002", percent2)
			var strData = JSON.stringify(data)
			publish(strData)
			percent2 = percent2 + 1
		}
	}, 2000);
	var percent3 = 26;
	var timeInterval2 = window.setInterval(function() {
		if (client.isConnected()) {
			if (percent3 >= 100) {
				percent3 = 10
			}
			var data = getDeviceData("003", percent3)
			var strData = JSON.stringify(data)
			publish(strData)
			percent3 = percent3 + 1
		}
	}, 2000);
}
init()
/*
 * var timer = setInterval(function(){ vue.devices.push({id: "0", deviceName:
 * "dRtv", deviceType: "SLA", area: "20-1000mm", power: "1000w", percent: 64}); },
 * 1000)
 */